package com.lz.myblog.controller;


import com.lz.myblog.entity.Articletypeinfo;
import com.lz.myblog.entity.Writingsinfo;
import com.lz.myblog.repository.ArticletypeRepository;
import com.lz.myblog.repository.WritingsRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller //注解为请求控制处理
@RequestMapping("/writings")
public class WritingsController {
    @Autowired
    WritingsRepository writingsRepository;//注入对象
    @Autowired
    ArticletypeRepository articletypeRepository;


    @RequestMapping("/add")  //跳转到添加页面
    public String add(Model model){
        List<Articletypeinfo> all = articletypeRepository.findAll();
        model.addAttribute("articletypeList",all);
        return "admin/writingsAdd";
    }

    @RequestMapping("/save")
    public String save(Writingsinfo writingsinfo){
        writingsRepository.save(writingsinfo);
        return "redirect:list";
    }

    @RequestMapping("/edit")
    public String edit(int writingsid,Model model){
        Writingsinfo one = writingsRepository.getOne(writingsid);
        model.addAttribute("one",one);
        List<Articletypeinfo> all = articletypeRepository.findAll();
        model.addAttribute("articletypeList",all);
        return "admin/writingsUpdate";
    }
    @RequestMapping("/update")
    public String update(Writingsinfo writingsinfo){
        writingsRepository.save(writingsinfo);
        return "redirect:list";
    }

    @RequestMapping("/detail")
    public String detail(int writingsid, Model model){
        Writingsinfo one = writingsRepository.getOne(writingsid);
        model.addAttribute("one",one);
        return "admin/writingsDetail";
    }

    @RequestMapping("/delete")
    public String delete(int writingsid){
        writingsRepository.deleteById(writingsid);
        return "redirect:list";
    }

    @RequestMapping("/list")
    public String list(Model model, Integer p){
        int pageSize = 5; //每页显示10条数据
        p = p==null?1:p; //判断是否传递了页码
//        p= p-1;
        Sort sort = Sort.by(Sort.Direction.DESC,"writingsid");  //排序条件
        Page<Writingsinfo> all = writingsRepository.findAll(PageRequest.of(p - 1, pageSize, sort));
        List<Writingsinfo> content = all.getContent();
        int totalPages = all.getTotalPages();
        //绑定参数
        model.addAttribute("content",content);
        model.addAttribute("totalPages",totalPages);
        model.addAttribute("currenPage",p);
        return "admin/writingsList";//跳转到jsp页面
    }
}
